<?php 

function doLogin(){
	//Read the client.ini file
	$ini = file_get_contents("client.ini");
	$iniArr = explode("\n" , $ini);
	$connArr = explode(":" , $iniArr[0]);
	//Grab server values from the ini file.
	$ip = $connArr['0']; $port = $connArr['1']; $current_version = $iniArr[1]; $email_offlines = $iniArr[2];
		
	//Declare the window object and set some properties for it
	$wnd = new GtkWindow();
	$wnd->set_title('A-Mess Login'); //It's title
	$wnd->set_position(Gtk::WIN_POS_CENTER); //Default position on screen
	$wnd->set_resizable(false); //Make it non resizable
	$wnd->connect_simple('destroy', array('Gtk', 'main_quit')); //Make it so if it's closed it'll cause main loop to exit too
	$wnd->set_icon_from_file(G . "images/ball_red.png");

	$vBox = new GtkVbox(); //Get a V(ertical) box in here
	$tblHdr = new GtkTable(1, 1, false); //Define the first table that'll only have 1 row and 1 column for our header
	$tbl = new GtkTable(3, 2, false); //Define the second table that'll contain all the widgets we need

	//Declare Objects needed in this window.
	$passObj = new GtkEntry(); $passLbl = new GtkLabel('Password:'); $passObj->set_width_chars(15); $passObj->set_visibility(false);
	$passLbl->set_alignment(0,0);
	$userObj = new GtkEntry(); $userLbl = new GtkLabel('Username:'); $userObj->set_width_chars(15);
	$userLbl->set_alignment(0,0);
	
	$button_register = create_img_button("Create A New Account", G . "images/register.png",
																				'verdana', '10', 'blue', '16', '16', '180', '28', 'horizontal');

	$connBtn = GtkButton::new_from_stock(Gtk::STOCK_CONNECT);
	$cancelBtn = GtkButton::new_from_stock(Gtk::STOCK_QUIT);
	$cancelBtn->connect_simple('clicked', array('Gtk', 'main_quit'));
	$hdr = GtkImage::new_from_file(G.'images/header.gif');


	$connBtn->connect_simple('clicked', 'connect', $ip, $port, $userObj, $passObj, $wnd);
	$button_register->connect_simple('clicked','newAcct', $ip, $port);

	//Header
	$tblHdr->attach($hdr, 0, 1, 0, 1, Gtk::FILL, Gtk::FILL);

	//Labels
	$tbl->attach($userLbl, 0, 1, 0, 1, Gtk::FILL, Gtk::FILL);
	$tbl->attach($passLbl, 1, 2, 0, 1, Gtk::FILL, Gtk::FILL);

	//Text Entires
	$tbl->attach($userObj, 0, 1, 1, 2, Gtk::FILL, Gtk::FILL);
	$tbl->attach($passObj, 1, 2, 1, 2, Gtk::FILL, Gtk::FILL);

	//Buttons
	$tbl->attach($connBtn, 1, 2, 3, 4, Gtk::FILL, Gtk::FILL);
	$tbl->attach($cancelBtn, 0, 1, 3, 4, Gtk::FILL, Gtk::FILL);

	//New account
	$tbl->attach($button_register, 0, 2, 4, 5, Gtk::FILL, Gtk::FILL);

	//Create the top menu bar
	$menubar = createMenubar($ip, $port, $wnd);
	$vBox->pack_start($menubar); //Add the menubar
	$vBox->pack_start($tblHdr); //Add first table to our vBox container
	$vBox->pack_start($tbl); //Add the second table to our vBox container. This will be added vertically under the first one due to usage of vBox and not hBox.
	 
	//Add the menu bar to the window
	$wnd->add($vBox);
	$wnd->show_all();	
	Gtk::main();
}

function connect($ip, $port, $userObj, $passObj, $wnd){
	$password = $passObj->get_text();
	$username = $userObj->get_text();
	//Check for connction
	if($fp = fsockopen($ip, $port, $errno, $errstr, 180)){
		$auth = "AUTH|NULL|".$username."#".md5($password)."\n";
		$md5 = strtolower(md5($username."^^".md5($password)));
		fwrite($fp, $auth);
		$resp = fread($fp, 1024); // Should read all list of buddies... never know how many the dude has got in his list though... should do something with while !feof
		fclose($fp);
		$respArr = explode("|", $resp);
		if($respArr[1] == "OK"){
			//Destroy the lgin window so they won't login again... Silly...
			$wnd->destroy();
			//Instantiate the receive object and set the socket hook
			$C = new Receive($ip, $port, $username, $password, $md5, $respArr);
		}else{
			$dlg = new GtkDialog("Invalid Login", $wnd, Gtk::DIALOG_MODAL, array(Gtk::STOCK_OK, Gtk::RESPONSE_OK, Gtk::STOCK_CANCEL, Gtk::RESPONSE_CANCEL));

			$dlg->set_position(Gtk::WIN_POS_CENTER);
			$dlg->set_icon_from_file(G . "images/ball_red.png");
			$dlg->connect_simple('destroy', 'backToLogin', $wnd, $dlg); //Catch the closing of the dialog
			$dialogQues = new GtkLabel("Invalid Login. Please retry.");
			$topArea = $dlg->vbox;
			$topArea->add($dialogQues);
			
			$dlg->show_all();

			$result = $dlg->run();

			switch($result) {
				case (Gtk::RESPONSE_OK):
					$dlg->destroy();
					break;
				case (Gtk::RESPONSE_CANCEL):
					Gtk::main_quit();
					break;
			}
			$dlg->destroy();
		}
	}else{
		connErr();
	}
}

function newAcct($ip, $port){
	//$wnd->hide();
	$sgnWnd = new GtkWindow();
	$sgnWnd->set_title('A-Mess Signup'); //It's title
	$sgnWnd->set_position(Gtk::WIN_POS_CENTER); //Default position on screen
	$sgnWnd->set_resizable(false); //Make it non resizable
	$sgnWnd->set_icon_from_file(G . "images/add_buddy.png");

	//Define some widgets present in this window (the SIGNUP window)
	$hdr = GtkImage::new_from_file(G.'images/header.gif');
	$okBtn = GtkButton::new_from_stock(Gtk::STOCK_OK);
	$cancelBtn = GtkButton::new_from_stock(Gtk::STOCK_CANCEL);
	//Labels
	$userLbl = new GtkLabel('Username (max 12 chars; NO special chars):');
	$userLbl->set_alignment(0,0);
	$passLbl = new GtkLabel('Password (max 22 chars; NO special chars):');
	$passLbl->set_alignment(0,0);
	$passVLbl = new GtkLabel('Confirm Password (max 22 chars; NO special chars):');
	$passVLbl->set_alignment(0,0);
	$emailLbl = new GtkLabel('Valid Email (NO special chars):');
	$emailLbl->set_alignment(0,0);
	//Entires
	$userEntry = new GtkEntry();
	$passEntry = new GtkEntry(); $passEntry->set_visibility(false);
	//$passVEntry = new GtkEntry(); $passVEntry->set_visibility(false);
	$emailEntry = new GtkEntry();

	$cancelBtn->connect_simple('clicked', 'cancelSingup', $sgnWnd);
	$okBtn->connect_simple('clicked', 'doSignup', $ip, $port, $userEntry, $passEntry, $emailEntry, $sgnWnd);
	
	$menubar = createMenubar($ip, $port, $sgnWnd);
	$vbox = new GtkVBox();
	$tblHdr = new GtkTable(1, 1, false);
	$tblSign = new GtkTable(8, 1, false);
	$tblBottom = new GtkTable(1, 2, false);
	
	//Attach header
	$tblHdr->attach($hdr, 0, 1, 0, 1);
	
	//Attach form
	$tblSign->attach($userLbl, 0, 1, 0, 1);
	$tblSign->attach($userEntry, 0,1,1,2);
	$tblSign->attach($passLbl, 0,1,2,3);
	$tblSign->attach($passEntry, 0,1,3,4);
	//$tblSign->attach($passVLbl, 0,1,4,5);
	//$tblSign->attach($passVEntry, 0,1,5,6);
	$tblSign->attach($emailLbl, 0,1,6,7);
	$tblSign->attach($emailEntry, 0,1,7,8);

	$tblBottom->attach($okBtn, 0, 1, 0, 1);
	$tblBottom->attach($cancelBtn, 1, 2, 0, 1);

	//Pack the menu bar
	$vbox->pack_start($menubar);
	//Pack more containers
	$vbox->pack_start($tblHdr);
	$vbox->pack_start($tblSign);
	$vbox->pack_start($tblBottom);

	$sgnWnd->add($vbox);
	$sgnWnd->show_all();
}


function lblImg($img, $txt){
	//Entire container for the label with image
	$lblBudContainer = new GtkHBox();
	$lblBudImage = GtkImage::new_from_file($img);
	$lblBudTxt   = new GtkLabel($txt);
	$lblBudContainer->pack_start($lblBudImage);
	$lblBudContainer->pack_start($lblBudTxt);

	return $lblBudContainer;
}

function createMenubar($ip, $port){
	//Create a simple menu bar
	$menubar = new GtkMenuBar();

	$options = new GtkImageMenuItem(Gtk::STOCK_HOME);
	$menubar->append($options);

	$mnuOpt = new GtkMenu();
	$newAcct = new GtkImageMenuItem(Gtk::STOCK_NEW);
	$quit = new GtkImageMenuItem(Gtk::STOCK_QUIT);
	$mnuOpt->append($newAcct);
	$mnuOpt->append($quit);
	$options->set_submenu($mnuOpt);
	 
	 
	//another menu item
	$about = new GtkImageMenuItem(Gtk::STOCK_ABOUT);
	$menubar->append($about);

	$mnuabout = new GtkMenu();
	$aboutAmess = new GtkMenuItem('About A-MESS');
	$mnuabout->append($aboutAmess);
	$about->set_submenu($mnuabout);
	$quit->connect_simple('activate',array('Gtk','main_quit'));
	$aboutAmess->connect_simple('activate','aboutDlg');
	$newAcct->connect_simple('activate','newAcct', $ip, $port);

	return $menubar;
}





function cancelSingup($sgnWnd){
	$sgnWnd->destroy();
}

function closeErr($errWnd){
	$errWnd->destroy();
}



function link_clicked($widget, $event, $title, $url) {
	$shell = new COM('WScript.Shell'); 
	$shell->Run('cmd /c start "" "' . $url . '"', 0, FALSE); 
	unset($shell);
}

function doSignup($ip, $port, $username, $password, $email, $sgnWnd){
	//Check if can connect to server
	if($fp = @fsockopen($ip, $port, $errno, $errstr, 180)){
		//Do Signup Right here
		$usernameA = substr($username->get_text() , 0 , 12);
		$usernameA = preg_replace('/[^a-z0-9]/', '', $usernameA); 
		
		$passwordA = $password->get_text();
		$passwordA = preg_replace('/[^a-z0-9]/', '', $passwordA); 
		$passwordA = md5($passwordA);
		
		$emailA = substr($email->get_text() , 0 , 150);
		$emailA = str_replace("#","",$emailA);
		
		
		$md5 = md5($username.$email.$password);
		
		$msg = "SIGNUP|".$usernameA."|".$md5."#".$usernameA."#".$passwordA."#".$emailA."#\n";
		fwrite($fp , $msg);
		
		$resp = fread($fp , 1024);
		$respArr = explode("#" , $resp);
		
		if($respArr[0] == "SUCCESS"){
			//Inform user that signup was a complete success.
			
			$err = new GtkWindow();
			$err->set_resizable(false);
			$err->set_modal(true);
			$err->set_title("REGISTRATION WAS A COMPLETE SUCCESS, FAKYAHH !");
			$err->set_position(Gtk::WIN_POS_CENTER);
			$err->set_icon_from_file(G . "images/chat.png");
			
			$tbl = new GtkTable();
			$lbl = new GtkLabel("Thank you commander ! Your registration was a COMPLETE success !");
			$lbl->modify_font(new PangoFontDescription("tahoma 9"));
			$lbl->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("blue"));
			
			$lblA = new GtkLabel("In exactly 10 minutes, you will receive an EMAIL at: ".$emailA." which will contain your account info.");
			$lblA->modify_font(new PangoFontDescription("tahoma 9"));
			$lblA->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("blue"));
			
			$btn = create_img_button("OK, GREAT !", G. "images/status.png", "tahoma", "9", "blue", "16", "16", "120", "28", "horizontal");
			
			$tbl->attach($lbl,0,1,0,1, Gtk::FILL, Gtk::FILL);
			$tbl->attach($lblA,0,1,1,2, Gtk::FILL, Gtk::FILL);
			$tbl->attach($btn,1,2,0,1, Gtk::SHRINK, Gtk::SHRINK);
			
			$btn->connect_simple('clicked' , 'destroy_err_more' , $err, $sgnWnd);
			
			$err->add($tbl);
			$err->show_all();
			
		}else{
			$erro = $respArr[1];
			//Inform user the opposite
			$err = new GtkWindow();
			$err->set_modal(true);
			$err->set_resizable(false);
			$err->set_title($erro);
			$err->set_position(Gtk::WIN_POS_CENTER);
			$err->set_icon_from_file(G . "images/chat.png");
			
			$tbl = new GtkTable();
			$lbl = new GtkLabel($erro);
			$lbl->modify_font(new PangoFontDescription("tahoma 9"));
			$lbl->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("blue"));
			$btn = create_img_button("OH, FOR FUCK SAKES !", G. "images/status.png", "tahoma", "9", "blue", 
											"16", "16", "160", "28", "horizontal");
			
			$tbl->attach($lbl,0,1,0,1, Gtk::FILL, Gtk::FILL);
			$tbl->attach($btn,0,1,1,2, Gtk::SHRINK, Gtk::SHRINK);
			
			$btn->connect_simple('clicked' , 'destroy_err' , $err);
			
			$err->add($tbl);
			$err->show_all();
		}
		
		@fclose($fp);
		unset($fp);
	}else{
		connErr();
	}
	unset($fp);
}
function destroy_err_more($err, $sgnWnd){
	$err->destroy();
	$sgnWnd->destroy();
}
function destroy_err($err){
	//print_r($err);
	//print_r($button);
	$err->destroy();
}


function connErr(){
	
	$errWnd = new GtkWindow();
	$errWnd->set_title('A-Mess Signup - SERVER ERROR'); //It's title
	$errWnd->set_default_size(200,50);
	$errWnd->set_position(Gtk::WIN_POS_CENTER); //Default position on screen
	$errWnd->set_resizable(false); //Make it non resizable
	$errWnd->set_modal(true);
	$errWnd->set_icon_from_file(G . "images/ball_red.png");
	$errWnd->connect_simple('destroy', 'closeErr', $errWnd); //Make it so if it's closed it'll cause main loop to exit too
	
	$errTbl = new GtkTable(3,1);

	//objects - widgets used here
	$errImg = GtkImage::new_from_stock(Gtk::STOCK_DIALOG_ERROR, Gtk::ICON_SIZE_DIALOG); // The error image
	$title = new GtkLabel("ERROR: Oh man, looks like server just took 5... Please try again later...");
	$title->modify_font(new PangoFontDescription("Arial Bold 11"));
	$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#FF0000"));
	$btn = GtkButton::new_from_stock(Gtk::STOCK_OK);

	$btn->connect_simple('clicked', 'closeErr', $errWnd);

	$errTbl->attach($errImg, 0,1,0,1);
	$errTbl->attach($title, 0,1,1,2);
	$errTbl->attach($btn, 0,1,2,3);
	
	$errVbox = new GtkVBox();
	$errVbox->pack_start($errTbl);
	$errWnd->add($errVbox);
	$errWnd->show_all();
	return true;
}


function sureDlg($stockImageID, $title, $label, $okFn, $canFn, $okParam, $canParam){
	$dlg = new GtkDialog($title, $wnd, Gtk::DIALOG_MODAL, array(Gtk::STOCK_OK, Gtk::RESPONSE_OK,Gtk::STOCK_CANCEL, Gtk::RESPONSE_CANCEL));
	$dlg->set_icon_from_file(G . "images/ball_red.png");
	$dlg->set_position(Gtk::WIN_POS_CENTER);

	$topArea = $dlg->vbox;
	$topArea->add(GtkImage::new_from_stock($stockImageID, Gtk::ICON_SIZE_DIALOG));
	$topArea->add(new GtkLabel(" "));
	$topArea->add(new GtkLabel($label));
	$topArea->add(new GtkLabel(" "));

	$dlg->show_all();

	$result = $dlg->run();

	switch($result) {
		case (Gtk::RESPONSE_OK):
			call_user_func($okFn, $okParam);
			break;
		case (Gtk::RESPONSE_CANCEL):
			call_user_func($canFn, $canParam);
			break;
	}

	$dlg->destroy();
}

function backToLogin($wnd, $dlg){
	$dlg->destroy();
}

function hupErr($nothing){
	$errWnd = new GtkWindow();
	$errWnd->set_title('WTF? Server...'); //It's title
	$errWnd->set_default_size(200,50);
	$errWnd->set_icon_from_file(G . "images/ball_red.png");
	$errWnd->set_position(Gtk::WIN_POS_CENTER); //Default position on screen
	$errWnd->set_resizable(false); //Make it non resizable
	$errWnd->set_modal(true);
	
	$errWnd->connect_simple('destroy', array('Gtk','main_quit')); //Make it so if it's closed it'll cause main loop to exit too
	
	$errTbl = new GtkTable(3,1);

	//objects - widgets used here
	$errImg = GtkImage::new_from_stock(Gtk::STOCK_DIALOG_ERROR, Gtk::ICON_SIZE_DIALOG); // The error image
	$title = new GtkLabel("Server has gone away... Click OK to exit and try again later...");
	$title->modify_font(new PangoFontDescription("Arial Bold 11"));
	$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#FF0000"));
	$btn = GtkButton::new_from_stock(Gtk::STOCK_OK);

	$btn->connect_simple('clicked', array('Gtk','main_quit'));

	$errTbl->attach($errImg, 0,1,0,1);
	$errTbl->attach($title, 0,1,1,2);
	$errTbl->attach($btn, 0,1,2,3);
	
	$errVbox = new GtkVBox();
	$errVbox->pack_start($errTbl);
	$errWnd->add($errVbox);
	$errWnd->show_all();
	return true;
}

function makeImgBtn($label, $image){
	//Do the enpty button
	$newBtn = new GtkButton();
	//Do a HBox container in the button
	$btnContainer = new GtkHBox();
	//Add the button to the HBox container
	$newBtn->add($btnContainer);
	//Do the image from a file or whatever
	$newImg=GtkImage::new_from_file($image);
	//Add the Image to that container
	$btnContainer->pack_start($newImg, 0, 0);
	//Add the text label next 2 it.
	$btnContainer->pack_start(new GtkLabel($label));

	return $newBtn;
}

function make_label($text , $font , $font_size , $color){
	$label = new GtkLabel($text);
	$label->modify_font(new PangoFontDescription($font." ".$font_size));
	$label->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse($color));
	return $label;
}

class Receive{
	public $tray;
	public $fp;
	public $budWnd;
	public $io_read;
	public $budSet;
	public $statSet;
	public $cell;
	public $model;
	public $column;
	public $iter;
	public $budArr = array();
	public $ip;
	public $port;
	public $password;
	public $username;
	public $responce;
	public $budStartChat = array();
	public $pixColumn;
	public $pixCell;
	public $md5;
	public $chatView = array();
	public $txtView = array();
	public $chatBuff = array();
	public $txtBuff = array();
	public $IMWindows = array();
	public $main;
	public $main_status;
	public $main_vbox;
	public $add_budd_wnd;
	public $add_bud_text;
	public $existent_buddies = array();
	public $err; 
	public $was_added;
	public $added_you;
	public $respArr = array();
	public $my_status;
	public $status_combo;


	public function __construct($ip , $port , $username , $password , $md5, $respArr){
		$this->ip = $ip;
		$this->port = $port;
		$this->username = $username;
		$this->password = $password;
		$this->md5 = $md5;
		$this->respArr = $respArr;
		$this->main_status = 1; // Set main windows status... hidden or active
		
		//Create a system tray icon
		$this->tray = new GtkStatusIcon();
		$this->tray->set_from_file(G . "images/status.png");
		$this->tray->connect('activate', array($this, 'on_activate'));
		
		//Do the buddies window and all that shizznit
		$this->main = new GtkWindow();
		
		$this->main->set_title('Welcome - '.$username); //It's title
		$this->main->set_position(Gtk::WIN_POS_CENTER); //Default position on screen
		$this->main->set_default_size(-1,600);
		$this->main->set_resizable(true); //Make it non resizable
		//Inform server I'm very offline if I destroy my window.....
		$this->main->connect_simple('destroy', array($this, 'write') , "QUIT|".$username."|".$md5."|\n");
		// , "QUIT|".$username."|".$md5."|\n"
		
		$this->main->set_icon_from_file(G . "images/status.png");
		
		//Objects needed
		$budMenu = $this->createBudMenubar();
		$hdr = GtkImage::new_from_file(G.'images/header.gif');
		
		
		//Make the add/remove buddy buttons...
		$btnAdd    = $this->create_img_button("Add", G . "images/add.gif", 'add_buddies_dialog' , 'tahoma', '7', 'blue', '14', '14', '70', '22', 'horizontal');
		$btnRemove = $this->create_img_button("Remove", G . "images/remove.gif", 'remove_buddies_dialog' , 'tahoma', '7', 'blue', '14', '14', '70', '22', 'horizontal');
		
		$btnTray = $this->create_img_button("Minimize", G . "images/tray.png", 'on_activate' , 'tahoma', 
												'7', 'blue', '14', '14', '70', '22', 'horizontal');
		
		$lblIdent = new GtkLabel();
		$lblIdent->set_markup("<span color='blue'><b>WELCOME: ".strtoupper($username)."</b></span>");
		$lblIdent->set_alignment(0,0);

		//Call the treeview method here
		$scrolled_win = new GtkScrolledWindow(); //Making it scrollable would be very nice...
		$scrolled_win->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
		$this->view = $this->buddyView($respArr);
		$this->view->connect('button-press-event', array($this, 'on_dbl_click'));
		$scrolled_win->add($this->view);
		
		$hdrTbl = new GtkTable();
		$tblLblBtnAdd = new GtkTable();
		$tblBudView = new GtkTable();

		//$hdrTbl->attach($hdr, 0,1,0,1,Gtk::SHRINK,Gtk::SHRINK);
		$hdrTbl->attach($lblIdent, 0,1,0,1,Gtk::SHRINK,Gtk::SHRINK);
		
		
		$tblLblBtnAdd->attach($btnAdd, 0,1,0,1,Gtk::SHRINK,Gtk::SHRINK);
		$tblLblBtnAdd->attach($btnRemove, 1,2,0,1,Gtk::SHRINK,Gtk::SHRINK);
		$tblLblBtnAdd->attach($btnTray, 2,3,0,1,Gtk::SHRINK,Gtk::SHRINK);
		
		$tblBudView->attach($scrolled_win, 0,1,0,1);
		
		$this->main_vbox = new GtkVBox();
		$this->main_vbox->pack_start($budMenu,0,0);
		$this->main_vbox->pack_start($hdrTbl,0,0);
		$this->main_vbox->pack_start($tblLblBtnAdd,0,0);
		$this->main_vbox->pack_start($tblBudView);
		
		$this->main->add($this->main_vbox);
		$this->main->show_all();
		
		//Initiate communication to server.
		$this->fp = fsockopen($ip, $port, $errno, $errstr, 180);
		fwrite($this->fp, "EHLO|".$username."|".$md5."|\n");
		$this->io_read = Gtk::io_add_watch($this->fp, Gobject::IO_IN | Gobject::IO_HUP, array($this,'read'));
		
		
		Gtk::main();
	}
	
	public function createBudMenubar(){
		//Create a simple menu bar
		$menubar = new GtkMenuBar();
	
		$options = new GtkImageMenuItem(Gtk::STOCK_HOME);
		$menubar->append($options);
	
		$mnuOpt = new GtkMenu();
		
		$quit = new GtkImageMenuItem(Gtk::STOCK_QUIT);
		$mnuOpt->append($quit);
		$options->set_submenu($mnuOpt);
		 
		 
		//another menu item
		$about = new GtkImageMenuItem(Gtk::STOCK_ABOUT);
		$menubar->append($about);
		$mnuabout = new GtkMenu();
		$aboutAmess = new GtkMenuItem('About A-MESS');
		$mnuabout->append($aboutAmess);
		$about->set_submenu($mnuabout);
		
		$quit->connect_simple('activate', array($this, 'write') , "QUIT|".$this->username."|".$this->md5."|\n");
		$aboutAmess->connect_simple('activate',array($this, 'aboutDlg'));
	
		return $menubar;
	}
	
	public function aboutDlg(){
		$dlg = new GtkDialog("About A-Mess Messenger (http://www.a-mazed.com)", $wnd, Gtk::DIALOG_MODAL, array(Gtk::STOCK_OK, Gtk::RESPONSE_OK));
		$dlg->set_position(Gtk::WIN_POS_CENTER);
		$dlg->set_icon_from_file(G . "images/ball_red.png");
	
		$clickLabel = new GtkHBox();
		$clickLabel->pack_start(new GtkLabel("Credits to: Ciprian Dimofte, Dan. Stoika, Luca Daniel -> Great men, HUGE ideas"), 0, 0);
		$clickLabel->pack_start(new GtkLabel(" and "), 0, 0);
		$clickLabel->pack_start($this->make_link("PHP-GTK2", "http://gtk.php.net/manual/en/"), 0, 0); 
	
		$clickLbl = new GtkHBox();
		$clickLbl->pack_start($this->make_link("http://www.a-mazed.com", "http://www.a-mazed.com"));
	
		$topArea = $dlg->vbox;
		$topArea->add(new GtkLabel("A-MESS V1.0 (beta)"));
		$topArea->add(new GtkLabel(" "));
		$topArea->add(new GtkLabel("Written by: Ciprian Dimofte - 2008"));
		$topArea->add(new GtkLabel(" "));
		$topArea->pack_start($clickLabel);
		$topArea->add(new GtkLabel(" "));
		$topArea->add(new GtkLabel("For more information please visit: "));
		$topArea->pack_start($clickLbl);
	
		$dlg->show_all();
	
		$result = $dlg->run();
		switch($result) {
			case (Gtk::RESPONSE_OK):
				$dlg->destroy();
				break;
		}
	
		$dlg->destroy();
	}
	
	public function make_link($title, $url) {
	    $label = new GtkLabel($title);
	    $label->set_markup('<span color="blue"><u>'.$title."</u></span>");
	    $eventbox = new GtkEventBox; // note 2
	    $eventbox->add($label);
	    $eventbox->connect('button-press-event', 'link_clicked', $title, $url);
	    return $eventbox;
	}
	
	public function make_label($text , $font , $font_size , $color){
		$label = new GtkLabel($text);
		$label->modify_font(new PangoFontDescription($font." ".$font_size));
		$label->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse($color));
		return $label;
	}
	
	public function add_buddies_dialog(){
		$this->add_bud_wnd = new GtkWindow();
		$this->add_bud_wnd->set_resizable(false);
		$this->add_bud_wnd->set_title("Hello ".$this->username."-> Add Buddy...");
		//$this->add_bud_wnd->set_size_request(350, 40);
		$this->add_bud_wnd->set_position(Gtk::WIN_POS_CENTER);
		$this->add_bud_wnd->set_icon_from_file(G . "images/chat.png");
		//$this->add_bud_wnd->connect_simple('destroy', array('Gtk','main_quit'));
		
		$tbl = new GtkTable();
		
		$enter_buddy_label = $this->make_label("Enter Username:", "tahoma", "10", "blue");
		$buddy_text = new GtkEntry(); $buddy_text->set_width_chars(25);
		$add_btn = $this->create_img_button("Add Now", G . "images/add_buddy.png", 'add_buddies', "tahoma", "8", "blue", "16", "16", "83", "26", "horizontal");
		
		$this->add_bud_text = $buddy_text;
		if($this->was_added){
			$this->was_added->destroy();
		}
		$this->add_bud_text->set_text($this->added_you);
		
		$tbl->attach($enter_buddy_label , 0,1,0,1, Gtk::SHRINK, Gtk::SHRINK);
		$tbl->attach($buddy_text , 1,2,0,1, Gtk::SHRINK, Gtk::SHRINK);
		$tbl->attach($add_btn , 2,3,0,1, Gtk::SHRINK, Gtk::SHRINK);
		
		$this->add_bud_wnd->add($tbl);
		$this->add_bud_wnd->show_all();
	}
	
	public function add_buddies(){
		unset($this->existent_buddies);
		$rows_to_remove = array();
		$to_add = $this->add_bud_text->get_text();
		$model = $this->view->get_model();
		
		
	    
		if(is_array($this->existent_buddies)){
			$key = array_search($to_add , $this->existent_buddies);
		}else{
			$key = false;
		}
		if($key !== false){
			
		}else{
			//This is where I send the request to the server to add this new buddy since everything seems to be in order... We will see if the server really
			//wants to add it though... based on database records...
			//echo "do here what needs to be done to add the buddy. Send request to server.";
			$string_send = "BUDADD|".$this->username."|".$this->md5."#".$to_add."\n";
			$this->write($string_send);
		}
	}
	
	public function array_search_recursive($needle, $haystack, $path=array()){
    	foreach($haystack as $id => $val){
         $path2=$path;
         $path2[] = $id;
 
         if($val === $needle)
              return $path2;
         else if(is_array($val))
              if($ret =$this->array_search_recursive($needle, $val, $path2))
                   return $ret;
      }
      return false;
	}
	
	public function remove_buddies_dialog(){
		//Debug string...
		//echo $this->ip."\n".$this->port."\n".$this->username."\n".$this->password."\n".$this->md5."\n";
		$dlg = new GtkDialog("Are you sure ?", $this->main, Gtk::DIALOG_MODAL, array(Gtk::STOCK_OK, Gtk::RESPONSE_OK,Gtk::STOCK_CANCEL, Gtk::RESPONSE_CANCEL));

		$dlg->set_position(Gtk::WIN_POS_CENTER);
	
		$topArea = $dlg->vbox;
		$topArea->add(GtkImage::new_from_stock(Gtk::STOCK_DIALOG_QUESTION, Gtk::ICON_SIZE_DIALOG));
		$topArea->add(new GtkLabel(" "));
		$topArea->add(new GtkLabel("Are you sure you want to remove the selected buddies ?"));
		$topArea->add(new GtkLabel(" "));
	
		$dlg->show_all();
	
		$result = $dlg->run();
	
		switch($result) {
			case (Gtk::RESPONSE_OK):
				call_user_func(array($this , 'remove_buddies'));
				break;
			case (Gtk::RESPONSE_CANCEL):
				break;
		}
	
		$dlg->destroy();
	}
	
	
	public function remove_buddies(){
		$remBuddy = array();
		$model = $this->view->get_model();
	    $selection = $this->view->get_selection();
	    list($model, $selected_rows) = $selection->get_selected_rows();

	    $i = 0;
	    $rows_to_remove = array();
		if(is_array($selected_rows)){
			foreach($selected_rows as $path) {
				$iter = $model->get_iter($path);
				$buddy = $model->get_value($iter, 0);
				//Remove from server here, one bye one mother fuckers...
				$remBuddy[] = $buddy;
				//echo $buddy." gone...\n";
				/////////
				++$i;
				$rows_to_remove[] = $path[0];
			}
	
			//Removing from server in one go
			//Check if can connect to server
			if($fp = @fsockopen($this->ip, $this->port, $errno, $errstr, 180)){
				//Do Remove Right here
				$to_remove = implode(">>" , $remBuddy);
				$strSend = "BUDREM|".$this->username."|".$this->md5."#".$to_remove."\n";
				fwrite($fp , $strSend);
				//echo "sending request to server. connection OK.";
				fclose($fp);
			}else{
				connErr();
			}
			
			for ($i=count($rows_to_remove)-1; $i>=0; --$i) {
				unset($model[$rows_to_remove[$i]]);
			}
			unset($rows_to_remove);
			unset($model);
			unset($selection);
		}
	}
	
	public function create_img_button($label, $img, $callback, $font_name, $font_size, $color, $width, $height, $sizew, $sizeh, $position) { 
		$button = new GtkButton(); // create a standard button
		$button->set_size_request($sizew, $sizeh);
		$button->connect('clicked', array($this , $callback));
		if($position == "horizontal"){$button_hbox = new GtkHBox();}else{$button_hbox = new GtkVBox();}
		$button->add($button_hbox);
		$imag = new GtkImage();
		$imge=GdkPixbuf::new_from_file($img)->scale_simple($width, $height, Gdk::INTERP_HYPER);
		$imag->set_from_pixbuf($imge);
		$button_hbox->pack_start($imag, 0, 0);
		$button_hbox->pack_start(new GtkLabel(), 0, 0); // THIS IS A FUCKING SPACER
		$btnLabel = new GtkLabel($label);
		$btnLabel->modify_font(new PangoFontDescription("{$font_name} {$font_size}"));
		$btnLabel->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse($color));
		$button_hbox->pack_start($btnLabel, 0, 0);
	
		return $button;
	}
	
	public function hide_main(){
		$this->main->hide_all();
		return false;
	}
	
	public function on_activate($status){
		if($this->main_status == 1){
			$this->main->hide_all();
			$this->main_status = 0;
		}else{
			$this->main->show_all();
			$this->main->grab_focus();
			$this->main->deiconify();
			$this->main_status = 1;
		}
	}
	
	public function destroy_added(){
		$this->was_added->destroy();
	}
	
	public function read($connection, $io_read){
		if($io_read == Gobject::IO_HUP){
			hupErr($nothing);
		}
		if($io_read == Gobject::IO_IN){
			$got = fread($this->fp, 19024);
			$gotArr = explode("#", $got);
			$type = $gotArr[1];
			//echo $type;
			//Treat some other sort of incoming requests from the server. Such as buddy-add request from some other users, etc.
			
			//Someone has added you
			if($type == "YOUWEREADDED"){
				//echo "You were added by " . $gotArr['2'] . "\n";
				
				$this->was_added = new GtkWindow();
				$this->was_added->set_resizable(false);
				$this->was_added->set_title("DUUDE, You GOT OWNED !");
				$this->was_added->set_position(Gtk::WIN_POS_CENTER);
				$this->was_added->set_icon_from_file(G . "images/chat.png");
				
				$tbl = new GtkTable();
				unset($this->added_you);
				$this->added_you = $gotArr['2'];
				$lbl = $this->make_label(strtoupper($gotArr['2']). " added you as a buddy..." , "tahoma" , "9" , "blue");
				$btn_whatever = $this->create_img_button("WHATEVER...", G. "images/status.png", 'destroy_added', "tahoma", "9", "blue", 
												"16", "16", "120", "28", "horizontal");
				$btn_add_too = $this->create_img_button("OK, FINE !", G. "images/add_buddy.png", 'add_buddies_dialog', "tahoma", "9", "blue", 
												"16", "16", "120", "28", "horizontal");
				
				$tbl->attach($lbl,0,1,0,1, Gtk::FILL, Gtk::FILL);
				$tbl->attach($btn_whatever,0,1,1,2, Gtk::FILL, Gtk::FILL);
				$tbl->attach($btn_add_too,1,2,1,2, Gtk::FILL, Gtk::FILL);
				
				$this->was_added->add($tbl);
				$this->was_added->show_all();
			}
			
			
			//Add a new buddy
			if($type == "BUDADD"){
				$added_status = $gotArr[2];
				$recv_md5 = $gotArr[3];
				if($recv_md5 = $this->md5){
					if($added_status == "SUCCESS"){
						//echo "It's ok to add him to the list.";
						
						//THIS ONLY HAPPENS AFTER SERVER SENT THE OK/SUCCESS. IN CASE SERVER SENT ERROR, THIS DOES NOT HAPPEN.
						$to_add = $this->add_bud_text->get_text();
						$model = $this->view->get_model();
						//First remove all from the fictional list
						$n = $model->iter_n_children(NULL);
					    for ($i=0; $i<$n; ++$i) {
					        $iter = $model->get_iter($i);
					        $path = $model->get_path($iter);
					        $current_buddy = $model->get_value($iter, 0);
					        $this->existent_buddies[] = $current_buddy;
					        $rows_to_remove[] = $path[0];
					    }
						for ($i=count($rows_to_remove)-1; $i>=0; --$i) {
							unset($model[$rows_to_remove[$i]]);
						}
						unset($rows_to_remove);
						//Put the values back to the listview
						//First add the new added buddy to the existent_buddies array
						$this->existent_buddies[] = $to_add;
						//Now sort the new list again (pfew...)
						sort($this->existent_buddies, SORT_STRING);
						//And add the new sorted list that includes the new buddy to the view.
						foreach ($this->existent_buddies as $bud){
							$model->append(array($bud));
						}
						unset($this->added_you);
						//Close the add buddy window
						$this->add_bud_wnd->destroy();
						/////////////////////////////////////////////////
					}else{
						$this->err = new GtkWindow();
						$this->err->set_modal(true);
						$this->err->set_resizable(false);
						$this->err->set_title($gotArr[2] . " " . $gotArr[4]);
						$this->err->set_position(Gtk::WIN_POS_CENTER);
						$this->err->set_icon_from_file(G . "images/chat.png");
						
						$tbl = new GtkTable();
						$lbl = $this->make_label($gotArr[2] . " " . $gotArr[4] , "tahoma" , "9" , "blue");
						$btn = $this->create_img_button("OK, GREAT !", G. "images/status.png", 'destroy_err', "tahoma", "9", "blue", 
														"16", "16", "120", "28", "horizontal");
						
						$tbl->attach($lbl,0,1,0,1, Gtk::FILL, Gtk::FILL);
						$tbl->attach($btn,0,1,1,2, Gtk::SHRINK, Gtk::SHRINK);
						
						$this->err->add($tbl);
						$this->err->show_all();
						
					}
				}
			}
		
			//We here treat all the online and offline goings of our buddies...
			if($type == "IQ_STATS"){
				$buddy = trim($gotArr[2]);
				$statusul = trim($gotArr[3]);
				$statusul = str_replace("\n","",$statusul);
				if($statusul != "OFFLINE"){
					if($statusul == "ONLINE"){
						//Play the ONLINE sound
						$this->budArr['online'][] = $buddy;
					}
				}else{
					//Play the OFFLINE sound
					

					$strCmp = $this->budArr['online'];
					for($j = 0 ; $j < count($strCmp) ; $j++){
						if($strCmp[$j] == $buddy){
							unset($this->budArr['online'][$j]);
							$this->budArr['online'] = array_values($this->budArr['online']);
						}
					}
				}
				$this->column->set_cell_data_func($this->cell, array($this, "set_status"));
				$this->pixColumn->set_cell_data_func($this->pixCell, array($this, "set_bullet"));
				return true;
			}
			

			//If we received a new IM message for the loggedin user...
			if($type == "IM"){
				$buddy = $gotArr[2];
				$time = $gotArr[4];
				$body = $gotArr[5];

				//Would be nice to setup some events based on the message body
				//(would be secure allthough anyone THAT IS LOGGED IN can create such messages)
				////////////////////////////////////////////////////////////////////////////////
				
				////////////////////////////////////////////////////////////////////////////////

				$found = array_search($buddy, $this->budStartChat);
				if($found === false){
					$this->budStartChat[] = $buddy;
					$bufID = $this->imWnd($buddy);
				}
				
				if($this->IMWindows[$buddy]){
					//Should do something here to make the window flash...
					$this->IMWindows[$buddy]->deiconify();
					////////////////////////////////////////////////////
				}
				
				//Get some unwanted stuff out of the message
				//These first 3 parts are used in the communication protocol
				$body = str_replace("#"," ",$body);
				$body = str_replace("|"," ",$body);
				$body = str_replace("^"," ",$body);
				//These are just nasty words...
				$body = str_replace("fuck","@!$",$body);
				$body = str_replace("shit","@!$",$body);


				

				$toGet = "\n<<<".$buddy." - ".date("F d Y - H:i:s", $time).">>>\n".$body;
				

				$iter = $this->chatBuff[$buddy]->get_end_iter();
				$this->chatBuff[$buddy]->insert($iter, $toGet);
				$this->chatBuff[$buddy]->place_cursor($this->chatBuff[$buddy]->get_end_iter());
				$this->chatView[$buddy]->scroll_to_mark($this->chatBuff[$buddy]->get_insert(), 0 , 1 , 0 , 1);

				
				$allTxt = $this->chatBuff[$buddy]->get_text($this->chatBuff[$buddy]->get_start_iter(), $this->chatBuff[$buddy]->get_end_iter());
				$tagTbl = $this->chatBuff[$buddy]->get_tag_table();
				$tag['Red'] = new GtkTextTag();
				$tag['Red']->set_property('foreground', "#FF0000");
				$tagTbl->add($tag['Red']);
				
				$posStart = strpos($allTxt, $toGet);
				$posEnd = $posStart+strlen($toGet);
				$this->chatBuff[$buddy]->apply_tag($tag['Red'], $this->chatBuff[$buddy]->get_iter_at_offset($posStart), $this->chatBuff[$buddy]->get_iter_at_offset($posEnd));

				

				return true;
			}
		}
		return true;
		
	}
	
	public function destroy_err(){
		$this->err->destroy();
	}

	public function on_drop($widget, $context, $x, $y, $data){
		$md5 = strtolower(md5($this->username."^^".$this->password));
		$listArr = explode("\n",$data->data);
		if(count($listArr) <= 5){
			foreach($listArr as $filename){
					if($filename && $filename != ""){
						$parse = parse_url($filename);
						$path = $parse['path'];
						$pathArr = explode("/", $path);

					}
			}
		}else{
			
		}
	}

	public function imWnd($buddy){
		$wndName = new GtkWindow();
		$wndName->set_accept_focus(true);
		$wndName->set_title($buddy);
		//$wndName->set_default_size(500,250);
		$wndName->set_position(Gtk::WIN_POS_CENTER);
		$wndName->set_resizable(false);
		$wndName->set_modal(false);
		$wndName->connect_simple("destroy", array($this,'closedIMWnd'), $buddy);
		$wndName->set_icon_from_file(G . "images/chat.png");

		//First add a vBox
		$vBox = new GtkVBox();
		
		$tbl = new GtkTable();

		//Draw user related objects
		$upView = new GtkTextView();
		$upView->modify_font(new PangoFontDescription("Verdana 8"));
		$upView->set_wrap_mode(Gtk::WRAP_WORD);
		$upView->set_property('can_focus' , FALSE);

		$upBuff = new GtkTextBuffer();
		$upView->set_buffer($upBuff);
		$upView->set_editable(false);

		$tagTbl = new GtkTextTagTable();;
		
		$scrolled_window = new GtkScrolledWindow();
		$scrolled_window->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
		$scrolled_window->add($upView);
		$scrolled_window->set_property('shadow-type', Gtk::SHADOW_OUT);
		$scrolled_window->set_size_request(650,380);

		$downView = new GtkTextView();
		$downView->modify_font(new PangoFontDescription("Verdana 10"));
		$downView->set_wrap_mode(Gtk::WRAP_WORD);
		$downBuff = new GtkTextBuffer();
		$downView->set_buffer($downBuff);

		//Set the drag/drop area
		$downView->drag_dest_set(Gtk::DEST_DEFAULT_ALL, array( array( 'text/uri-list', 0, 0)), Gdk::ACTION_COPY);
		$downView->connect('drag-data-received', array($this,'on_drop'));
		$upView->drag_dest_set(Gtk::DEST_DEFAULT_ALL, array( array( 'text/uri-list', 0, 0)), Gdk::ACTION_COPY);
		$upView->connect('drag-data-received', array($this,'on_drop'));

		//Define the text boxes and windows for each buddy in part
		$this->chatView[$buddy] = $upView;
		$this->txtView[$buddy] = $downView;

		$this->chatBuff[$buddy] = $upBuff;
		$this->txtBuff[$buddy] = $downBuff;

		$this->IMWindows[$buddy] = $wndName;
		////////////////////////////////////
		
		$downView->connect('key-press-event', array($this,'on_key_press'), $this->chatView[$buddy], $this->chatBuff[$buddy], $this->txtView[$buddy], $this->txtBuff[$buddy], $buddy);
		$down_scrolled = new GtkScrolledWindow();
		$down_scrolled->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
		$down_scrolled->add($downView);
		$down_scrolled->set_property('shadow-type', Gtk::SHADOW_OUT);
		$scrolled_window->set_size_request(650,380);

		$tbl->attach($scrolled_window, 0,1,0,1 , Gtk::FILL , Gtk::FILL);
		$tbl->attach($down_scrolled, 0,1,1,2 , Gtk::FILL , Gtk::FILL);

		
		$vBox->pack_start($tbl);
		$downView->grab_focus();

		

		$wndName->add($vBox);
		$wndName->show_all();

		return $wndName;
	}

	public function on_key_press($widget, $event, $view1, $buffer1, $view2, $buffer2, $buddy) {
		$input = $buffer2->get_text($buffer2->get_start_iter(), $buffer2->get_end_iter());
		$MAXinput = $buffer2->get_text($buffer2->get_start_iter(), $buffer2->get_iter_at_offset(1049));
		if(strlen($input) > 500){
			$buffer2->set_text($MAXinput);
		}
		
		
		
		if($event->keyval==Gdk::KEY_Return) {
			if ($event->state & Gdk::SHIFT_MASK) return false;
			$input = $MAXinput;
			$iter = $buffer1->get_end_iter();
			$toAdd = "\n<<<".$this->username." - ".date("F d Y - H:i:s").">>>\n".$input;
			
			if(strlen($input) >= 2){
				$buffer1->insert($iter, $toAdd);
				$buffer1->place_cursor($buffer1->get_end_iter());
				$view1->scroll_to_mark($buffer1->get_insert(), 0 , 1 , 0 , 1);
				$buffer2->set_text('');
			}
			
			$md5 = strtolower(md5($this->username."^^".$this->password));
			$input = str_replace("#"," ",$input);
			$input = str_replace("|"," ",$input);
			$input = str_replace("^"," ",$input);
			$input = str_replace("fuck","@!$",$input);
			$input = str_replace("shit","@!$",$input);
			
			$strSend = "IM|".$this->username."|".$md5."#IM#".$this->username."#".$buddy."#".time()."#".$input."#\n";
			if(strlen($input)>=2){
				$this->write($strSend);
			}
			return true;
		}else{
			return false;
		}
	}

	public function closedIMWnd($buddy){
		//unset that value from the IM windows array first
		$key = array_search($buddy, $this->budStartChat);
		unset($this->budStartChat[$key]);
		$this->budStartChat = array_values($this->budStartChat);
		unset($this->chatView[$buddy], $this->chatBuff[$buddy], $this->txtView[$buddy], $this->txtBuff[$buddy], $this->IMWindows[$buddy]);

		
	}

	public function set_bullet($column, $cell, $model, $iter){
		$path = $model->get_path($iter);
		$row_num = $path[0];
		$buddyList = $model->get_value($iter, 0);
		$cell->set_property('pixbuf', GdkPixbuf::new_from_file(G."images/ball_red.png"));
		if(is_array($this->budArr['online'])){
			for($it = 0 ; $it < count($this->budArr['online']) ; $it++){
				$budsON = $this->budArr['online'][$it];
				if ($buddyList == $budsON){
					$cell->set_property('pixbuf', GdkPixbuf::new_from_file(G."images/ball_green.png"));
				}
			}
		}
		return true;
	}

	public function set_status($column, $cell, $model, $iter){
		$path = $model->get_path($iter);
		$row_num = $path[0];
		$buddyList = $model->get_value($iter, 0);
		//Set foreground and background to initial null
		$cell->set_property('foreground-set', 0);
		$cell->set_property('background-set', 0);
		//print_r($this->budArr['online']);

		if(is_array($this->budArr['online'])){
			for($it = 0 ; $it < count($this->budArr['online']) ; $it++){
				$budsON = $this->budArr['online'][$it];
				if ($buddyList == $budsON){
					$cell->set_property('foreground', "#663300");
					$cell->set_property('background', "#66FF00");
					$cell->set_property('foreground-set', 1);
					$cell->set_property('background-set', 1);
				}
			}
		}
		return true;
	}

	public function on_dbl_click($view, $event){
		$model = $this->model;
		if ($event->type == Gdk::_2BUTTON_PRESS) {
			
			$selection = $view->get_selection();
			@list($model, $selected_rows) = $selection->get_selected_rows();
			if(count($selected_rows)>0){
				$iter = $model->get_iter($selected_rows[0]);
				$buddy = $model->get_value($iter, 0);
			}

			//Start chat here !!!
			$found = array_search($buddy, $this->budStartChat);
			if($found === false){
				$this->budStartChat[] = $buddy;
				if($buddy){
					$wndID = $this->imWnd($buddy);
				}
			}
			////////////////////////
		}
	}

	public function buddyView($respArr){
		$this->responce = $respArr;
		//Make the treeview... pfew... this should be at least interesting...
		$model = new GtkListStore(Gobject::TYPE_STRING);
		$this->model = $model;
		$budView = new GtkTreeView($model);
		$budView->set_enable_search(true); 

		//SETUP THE FIRST COLUMN (BUDDIES LIST)
		$column = new GtkTreeViewColumn();

		$pix_cell_renderer = new GtkCellRendererPixbuf();
		$column->pack_start($pix_cell_renderer, false);

		$pix_cell_renderer->set_property('pixbuf', GdkPixbuf::new_from_file(G."images/ball_red.png"));

		$this->pixColumn = $column;
		$this->pixCell = $pix_cell_renderer;
		
		
		$cell_renderer = new GtkCellRendererText();
		$cell_renderer->set_property("xalign", 0.0);
		
		$this->cell = $cell_renderer;

		$column->pack_start($cell_renderer, true); 
		$column->set_attributes($cell_renderer, 'text', 0); 
		$column->set_alignment(0.0);
		

		// set the header font and color
		$label = new GtkLabel('My Buddies List');
		$label->modify_font(new PangoFontDescription("Arial Bold"));
		$label->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000FF"));
		$column->set_widget($label);
		$label->show();
		$this->column = $column;
		

		$budView->append_column($column);

		//Add buddies to TreeView (ListStore)
		
		$budListArr = explode("#", $respArr[2]);
		sort($budListArr, SORT_STRING);
		foreach($budListArr as $buddy){
			if($buddy != "OK" && $buddy != "\n" && $buddy){
				$model->append(array($buddy));
			}
		}
		$selection = $budView->get_selection();
		$selection->set_mode(Gtk::SELECTION_MULTIPLE);
		
		return $budView;
	}

	public function write($msg){
		$fpp = fsockopen($this->ip, $this->port, $errno, $errstr, 180);
		fwrite($fpp, $msg);
		fclose($fpp);
		$msgArr = explode("|",$msg);
		if($msgArr[0] == "QUIT"){
			unset($this->tray);
			@fclose($this->fp);
			unset($this->fp);
			Gtk::main_quit();
		}
	}
}

 

doLogin();
?>